package com.xindaoapp.framework.http;

// Static wrapper library around AsyncHttpClient

/**
 * 访问网络工具
 */
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.framework.api.ConstantsValue;
import com.xindaoapp.framework.application.XindaoApplication;
import com.xindaoapp.framework.utils.CommonLog;
import com.xindaoapp.framework.utils.CommonUtil;
import com.xindaoapp.framework.utils.xdConfig;

public class XDHttpClient {
	protected static CommonLog log = new CommonLog();
	private static AsyncHttpClient client = new AsyncHttpClient();

	public static void get(String api, RequestParams params, AsyncHttpResponseHandler responseHandler) {

		String absoluteUrl = getAbsoluteUrl(api);
		if (absoluteUrl.indexOf("?") != -1) {
			log.i(getAbsoluteUrl(api) + "&" + params.toString());
		} else {
			log.i(getAbsoluteUrl(api) + "?" + params.toString());
		}
		if (ConstantsValue.cookieStore != null) {
			client.setCookieStore(ConstantsValue.cookieStore);
		}
		client.get(getAbsoluteUrl(api), params, responseHandler);
	}

	public static void get2(String api, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		if (ConstantsValue.cookieStore != null) {
			client.setCookieStore(ConstantsValue.cookieStore);
		}
		client.get(api, params, responseHandler);
	}

	public static void post(String api, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		if (ConstantsValue.cookieStore != null) {
			client.setCookieStore(ConstantsValue.cookieStore);
		}
		log.i(getAbsoluteUrl(api) + params.toString());
		client.post(getAbsoluteUrl(api), params, responseHandler);
	}

	public static void post2(String api, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		// 检查网络
		if (CommonUtil.isNetworkAvailable(XindaoApplication.get().getApplicationContext()) == 0) {
			responseHandler.onFailure(null, "no have network");
		} else {
			if (ConstantsValue.cookieStore != null) {
				client.setCookieStore(ConstantsValue.cookieStore);
			}
			client.post(api, params, responseHandler);
		}

	}

	public static String getAbsoluteUrl(String relativeUrl) {
		return xdConfig.HOST_URL + relativeUrl;
	}

}
